const gulp = require('gulp'),
    htmlmin = require('gulp-htmlmin'),
    cleanCss = require('gulp-clean-css'),
    uglify = require('gulp-uglify'),
    babel = require('gulp-babel'),
    del = require('del'),
    connect = require('gulp-connect'),
    sass = require('gulp-sass')
    //每次开启之前删除dist
const delDist = () => del(['dist'])

//为了方便把 地址方path里面
const path = {
    html: {
        src: 'wrap/**/*.html',
        dest: 'dist'
    },
    css: {
        src: 'wrap/css/**/*.scss',
        dest: 'dist/css'
    },
    js: {
        src: 'wrap/js/**/*.js',
        dest: 'dist/js'
    },
    img: {
        src: 'wrap/images/**/*',
        dest: 'dist/images'
    },
    libs: {
        src: 'wrap/libs/**/*',
        dest: 'dist/libs'
    }
}

// 制定html任务：通过函数的方式
const html = () => {
    return gulp.src(path.html.src)
        .pipe(htmlmin({
            removeComments: true, //清除HTML注释
            collapseWhitespace: true, //压缩HTML
            collapseBooleanAttributes: true, //省略布尔属性的值 <input checked="true"/> ==> <input checked />
            removeEmptyAttributes: true, //删除所有空格作属性值 <input id="" /> ==> <input />
            removeScriptTypeAttributes: false, //删除<script>的type="text/javascript"
            removeStyleLinkTypeAttributes: true, //删除<style>和<link>的type="text/css"
            minifyJS: true, //压缩页面JS
            minifyCSS: true //压缩页面CSS 
        }))
        .pipe(gulp.dest(path.html.dest))
        .pipe(connect.reload())
}

//css
const css = () => {
        return gulp.src(path.css.src) //原本地址
            .pipe(sass())
            .pipe(cleanCss()) //压缩
            .pipe(gulp.dest(path.css.dest)) //压缩到
            .pipe(connect.reload())
    }
    //JS
const js = () => {
        return gulp.src(path.js.src)
            .pipe(babel({
                presets: ['@babel/env']
            }))
            .pipe(uglify())
            .pipe(gulp.dest(path.js.dest))
            .pipe(connect.reload())
    }
    //img
const img = () => {
        return gulp.src(path.img.src)
            .pipe(gulp.dest(path.img.dest))
    }
    //libs
const libs = () => {
    return gulp.src(path.libs.src)
        .pipe(gulp.dest(path.libs.dest))
}

//创建服务器
const server = () => {
    connect.server({
        root: 'dist',
        livereload: true, //热更新
        port: 2124
    })
}

//添加一个监听事件 wacth
const wacth = () => {
    gulp.watch(path.html.src, html)
    gulp.watch(path.css.src, css)
    gulp.watch(path.js.src, js)
}

// module.exports = { //让他们暴露出去
//     dist,
//     html,
//     css,
//     js,
//     img,
//     libs
// }
//每次先删除dist文件  在进行压缩处理  只需要输入gulp就可以运行了
module.exports.default = gulp.series(delDist, gulp.parallel(html, css, js, img, libs, server, wacth))